import { useCall, useEffectRef, useQueryValue } from '@/components';
import { SelectCompany } from '@/pages/components';
import { pathJoinParams } from '@/utils';
import PropTypes from 'prop-types';
import React, { useMemo, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';

function LinkWithSelectCompany({ beforeNavigate, to, replace = false, ...props }) {
  const history = useHistory();
  const location = useLocation();
  const ref = useRef();
  const locationRef = useEffectRef(location);
  const companyCode = useQueryValue('companyCode');
  const selectedRowKeys = useMemo(() => (companyCode ? [companyCode] : []), [companyCode]);
  const visible = Boolean(useQueryValue('selectCompany'));

  const waitNextLocation = useCall(() => {
    return new Promise((resolve) => {
      const timer = setInterval(() => {
        if (locationRef.current !== location) {
          clearInterval(timer);
          resolve();
        }
      });
    });
  });

  const onOk = useCall(async ([row]) => {
    await beforeNavigate?.(row);
    const navigate = replace ? history.replace : history.push;
    let next = to;
    const params = { companyCode: row.code, companyName: row.name };
    if (typeof next === 'string') {
      next = pathJoinParams(next, params);
    } else {
      next.search = pathJoinParams(next.search, params);
    }

    if (!replace) {
      // 非replace的链接，返回默认打开
      waitNextLocation().then(() => {
        navigate(next);
      });
      history.replace(pathJoinParams(location.pathname, location.search, { companyCode: row.code }));
    } else {
      navigate(next);
    }
  });

  const onToggle = useCall((open) => {
    if (open) {
      history.push(pathJoinParams(location.pathname, location.query, { selectCompany: true }));
    }
  });

  return (
    <SelectCompany
      ref={ref}
      {...props}
      visible={visible}
      onToggle={onToggle}
      selectedKeys={selectedRowKeys}
      onOk={onOk}
      onCancel={history.goBack}
    />
  );
}

LinkWithSelectCompany.propTypes = {
  /** 跳转前回调函数 (支持异步) */
  beforeNavigate: PropTypes.func,

  /** 路由路径或location对象 */
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,

  /** 是否替换当前历史路径 */
  replace: PropTypes.bool,
};

export default LinkWithSelectCompany;
